package com.itcam.cm.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.itcam.cm.manager.listener.CategoryReadListener;
import com.itcam.cm.manager.mapper.CategoryMapper;
import com.itcam.cm.manager.service.CategoryService;
import com.itcam.cm.model.entity.product.Category;
import com.itcam.cm.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        List<Category> categories = categoryMapper.selectByParentId(parentId);
        for (Category category : categories) {
            Long i = categoryMapper.countChildren(category.getId());
            if(i<=0){
                category.setHasChildren(false);
            }
        }
        return categories;
    }

    @SneakyThrows
    @Override
    public void importData(MultipartFile multipartFile) {
        InputStream inputStream = multipartFile.getInputStream();
        EasyExcel.read(inputStream, CategoryExcelVo.class,new CategoryReadListener(categoryMapper)).sheet("分类数据").doRead();
    }

    @SneakyThrows
    @Override
    public void exportData(HttpServletResponse response) {
        List<CategoryExcelVo> categoryExcelVos = new ArrayList<>();
        List<Category> categories = new ArrayList<>();
        categories = categoryMapper.selectAll();
        for(Category category : categories) {
            CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
            BeanUtils.copyProperties(category, categoryExcelVo, CategoryExcelVo.class);
            categoryExcelVos.add(categoryExcelVo);
        }
        EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("test").doWrite(categoryExcelVos);
    }
}
